import useCommon from '../common/common.js';
import { ref, onBeforeMount, inject, getCurrentInstance, watch, nextTick } from 'vue';
import dayjs from 'dayjs';
import core from '@common/core'
const request = core.getExportResource('src/core/utils/http-tools.js').default;
export function useProjectCreate() {
  const { commandFunc } = inject('apiFunTools');
  const { proxy } = getCurrentInstance();
  // 附件组件实例
  const upload = ref(null);
  // 类型组件配置
  const typeOptions = ref({
    otype: 'ty.inteplm.project.CTyProject',
    placeholder: proxy.$t('plsSelect')
  });
  // 计划时间组件配置
  const planOptions = ref({
    type: 'daterange',
    startPlaceholder: proxy.$t('startTime'),
    endPlaceholder: proxy.$t('endTime')
  });
  const templateTree = ref([]);
  const templatePopoverVisible = ref(false);
  const treeRef = ref(null);
  const selectedTemplateName = ref('');

  //获取项目模板下拉数据
  async function ProjectTemplateList() {
    // 只有当通过开发令回显数据后才能获取模板列表
    if (!isFromDevOrder.value) {
      templateTree.value = [];
      return;
    }
    const enumRes = await getEnum();
    for (const item in enumRes.data.pushMode) {
      if(formData.value.boost === enumRes.data.pushMode[item]){
        formData.value.boost = item;
        break ;
      }
    }
    for (const item in enumRes.data.developmentLevel) {
      if(formData.value.devCategory === enumRes.data.developmentLevel[item]){
        formData.value.devCategory = item;
        break ;
      }
    }
    console.log("boost",formData.value.boost,"devLevel", formData.value.devCategory);
    console.log("Enum数据：",enumRes);
    const params = {
      pushMode: formData.value.boost || 'QuickOpen',
      developmentLevel: formData.value.devCategory || 'GradeC'
    };

    try {
      const res = await getProjectTemplateList(params);
      if (res && res.success && res.data) {
        // 将整个 res.data 作为根节点，包含 "项目模板库"
        templateTree.value = [res.data];
      } else {
        templateTree.value = [];
      }
    } catch (error) {
      console.error('获取项目模板列表失败:', error);
      templateTree.value = [];
    }
  }

  // 用户组件配置
  const useOptions = ref({
    multiple: false,
    tabList: ['user'],
    triggerEl: 'input',
    showConfirmButton: false,
    showInput: false,
    labelKey: 'displayName',
    valueKey: 'oid',
    triggerElOptions: {
      clearable: true,
      placeholder: proxy.$t('plsSelect')
    }
  });
  const name = sessionStorage.getItem('userName');
  const fullname = sessionStorage.getItem('fullname');
  const oid = sessionStorage.getItem('userID');
  const otype = sessionStorage.getItem('userOtype');
  // 项目库新建默认值
  const formData = ref({
    planDate: [new Date(), dayjs(new Date()).add(1, 'year')],
    owner: [
      {
        name,
        fullname,
        oid,
        otype,
        displayName: `${fullname || ''}${name ? `(${name})` : ''}`
      }
    ],
    projectManagerList: [
      {
        rowValue: oid,
        rowLabel: `${fullname || ''}${name ? `(${name})` : ''}`,
        oid,
        otype,
        name,
        fullname,
        description: fullname
      }
    ],
    projectTemplateObj: {}
  });

  
  const {
    getEnum,
    formRef,
    ibaForm,
    tyProjectForm,
    phaseOptions,
    isAddparameter,
    getPhaseList,
    getNotSpecialChar,
    validatorName,
    validatorNumber,
    valideIbaForm,
    getIbaForm,
    queryDevOrderByNumber,
    queryDevOrderDetailByProjectCode,
    getProjectTemplateList,
    getIbaFormpro
  } = useCommon(formData);
  // 表单校验规则
  const rules = ref({
    typeOid: [{ required: true, trigger: 'blur', message: `${proxy.$t('projectType')}${proxy.$t('required')}` }],
    name: [{ required: true, validator: validatorName, trigger: 'blur' }],
    projectNumber: [{ required: true, validator: validatorNumber, trigger: 'blur' }],
    planDate: [{ required: true, trigger: 'blur', message: `${proxy.$t('planDate')}${proxy.$t('required')}` }],
    planTemplateName:[{ required: true, message: `${proxy.$t('项目模板')}${proxy.$t('required')}` }],
    description: [
      {
        trigger: 'blur',
        max: 1024,
        message: proxy.$t('basic.message.maxLength', {
          length: 1024
        })
      }
    ]
  });
  // 类型变化联动
  const change = (value, label, data) => {
    formData.value.category = label?.length ? label[0] : '';
    formData.value.typeOtype = data?.otype;
    getIbaForm(data?.logicalidentifier);
    nextTick(() => {
      formRef?.value?.getFormRef()?.validateField(['typeOid']);
    });
  };

  // 切换下拉列表显示状态
  const toggleDropdown = () => {
    templatePopoverVisible.value = !templatePopoverVisible.value;
  };

  // 点击外部关闭下拉列表
  const handleClickOutside = (event) => {
    if (templatePopoverVisible.value) {
      templatePopoverVisible.value = false;
    }
  };

  const handleNodeClick = (data, node) => {
    const modeMAP = {
      "Account": "大客户",
      "None": "无"
    };
    if(data.developmentMode){
      console.log("😍",data,node,formData.value.tyProjectForm.formData);
    }
    if (data.otype === 'ty.projectmng.admin.CTyProjectTemplate') {
      //检查是否为草稿模板
      if (data.name && data.name.includes('草稿')) {
        proxy.$message.warning('不能选择草稿模板');
        return;
      }
      //修改拓展属性-客户
      for (const item of formData.value.tyProjectForm.formData) {
        if(item.ibaDefDisplayName == "大类/客户"){

          item.value = modeMAP[data.developmentMode] ?? "";;
        }
      }

      formData.value.planTemplateOID = data.projectOID;
      formData.value.planTemplateOTYPE = data.projectOTYPE;
      formData.value.planTemplateName = data.name;
      selectedTemplateName.value = data.name;
      changeTemplate(data);
      templatePopoverVisible.value = false; // 选中后关闭下拉列表
    } else {
      if (node) {
        node.expanded = !node.expanded;
      }
    }
  };

  // 项目模板变化联动
  const changeTemplate = (item) => {
    const callback = (res) => {
      formData.value.projectTemplateObj.templateStartDate = res.startDate;
      formData.value.projectTemplateObj.templateFinishDate = res.finishDate;
    };
  };

  onBeforeMount(() => {
    getPhaseList();
    getNotSpecialChar();
    queryDevOrderByNumber();
  });

  // 项目开发令弹窗相关
  const dialogVisible = ref(false);
  const tableData = ref([]);
  const total = ref(0);
  const currentPage = ref(1);
  const pageSize = ref(5); // 每页显示5条
  const selectedRow = ref(null);
  const tableRef = ref(null);
  const devOrderDetail = ref(null); // 新增：开发令详细信息
  const isFromDevOrder = ref(false); // 新增：标记是否通过开发令回显

  // 新增：开发令查询输入和方法
  const searchDevOrderNumber = ref('');

  // 添加isNewSearch参数来明确控制是否重置页码
  const searchDevOrder = async (bool = false, isNewSearch = false) => {
    // 确保参数是布尔类型
    bool = typeof bool === 'boolean' ? bool : false;
    isNewSearch = typeof isNewSearch === 'boolean' ? isNewSearch : false;
    
    const ibaProData = await getIbaFormpro(); // 获取映射
    if(bool){
      searchDevOrderNumber.value = "";
      // 在清空搜索内容时重置页码为1
      currentPage.value = 1;
    }
    
    // 在执行新搜索时也需要重置页码为1，确保从第一页开始显示结果
    if (isNewSearch) {
      currentPage.value = 1;
    }
    
    const { data, total: t } = await queryDevOrderByNumber(searchDevOrderNumber.value || formData.value.projectDevOrder, currentPage.value, pageSize.value);

    if (data && data.length && ibaProData && ibaProData.success) {
      const ibaMap = ibaProData.data;
      tableData.value = (data || []).map((item) => ({
        id: item.id,
        dev: item.dev,
        model: item.model,
        number: item.number,
        sector:item.sector,
        productSeries:item.productSeries,
        name: item.name,
        level: ibaMap.developmentLevel[item.level] || item.level,
        subLevel: item.subLevel,
        system: item.system,
        owner: item.owner,
        boost: ibaMap.pushMode[item.boost] || item.boost,
        developmentType: item.developmentType,
        productCategory: item.productCategory,
      }));
      total.value = t;
      dialogVisible.value = true;
    } else {
      proxy.$message.warning('未查询到相关项目开发令');
    }
  };

  // 新增：清空搜索功能
  const clearSearch = () => {
    formData.value.projectDevOrder = "";
    searchDevOrderNumber.value = '';
    tableData.value = [];
    total.value = 0;
    currentPage.value = 1;
    selectedRow.value = null;
    searchDevOrder(true);
  };

  function onSearchProjectDevOrder() {
    dialogVisible.value = true;
  }
  function handleCurrentChange(row) {
    selectedRow.value = row;
  }
  function handlePageChange(page) {
    currentPage.value = page;
    searchDevOrder();
  }

  async function handleConfirm() {
    if (selectedRow.value) {
      formData.value.projectDevOrder = selectedRow.value.number;
      const detail = await queryDevOrderDetailByProjectCode(selectedRow.value.number);
      const ibaProData = await getIbaFormpro();

      if (detail && ibaProData && ibaProData.success) {
        const ibaMap = ibaProData.data;
        console.log('ibaMap', ibaMap);
        console.log(formData.value);
        const enumRes = await getEnum();
    for (const item in enumRes.data.pushMode) {
      if(formData.value.boost === enumRes.data.pushMode[item]){
        formData.value.boost = item;
        break ;
      }
    }
    for (const item in enumRes.data.developmentLevel) {
      if(formData.value.devCategory === enumRes.data.developmentLevel[item]){
        formData.value.devCategory = item;
        break ;
      }
    }
        // 这里做字段映射
        formData.value.name = detail.projectName || '';
        //formData.value.projectNumber = c.projectCode || '';
        formData.value.aircraftModel = detail.aircraftModel || '';
        formData.value.devCategory = detail.devCategory || '';
        formData.value.devLevel = detail.devLevel || '';
        formData.value.coefficient = detail.coefficient || '';
        //formData.value.projectManagerList = detail.responsiblePerson ? [{ displayName: detail.responsiblePerson }] : [];
        formData.value.remarks = detail.remarks || '';
        formData.value.boost = detail.boost || '';
        formData.value.developmentType = detail.DevelopmentType || '';
        formData.value.productSeries = detail.productSeries || '';
        formData.value.sector = detail.sector || '';
        formData.value.productCategory = detail.productCategory || '';
                      

        devOrderDetail.value = detail;
        isFromDevOrder.value = true;

        await ProjectTemplateList();

        // 将接口返回的相关字段同步到扩展属性表单
        const extMap = {
          DevelopmentOrder: detail.devOrderNumber,
          MachineModel: detail.aircraftModel,
          productType:detail.aircraftModel,
          DevelopmentLevel: ibaMap.developmentLevel[detail.devCategory] || detail.devCategory,
          Grade: detail.devLevel,
          Coefficient: detail.coefficient,
          PushMode: ibaMap.pushMode[detail.boost] || detail.boost,
          ProjectDevelopmentOrder: detail.projectCode,
          DevelopmentType: detail.developmentType,
          ProductSeries:detail.productSeries,
          ProjectSection:detail.sector,
          ProductCategory:detail.productCategory,//产品类别
        };
      //   const leiName = `${extMap.DevelopmentOrder}+${extMap.productType}`;  //产品类别接口
      //   console.log("leiName返回值：",leiName);
      //   let nameRes = await request({
      //     method: 'get',
      //     url: '/rest/v1/devorder/querySeriesByDevCode',
      //     params: {
      //       name:leiName,
      //     },
      // });
      // console.log("返回值：",nameRes.data.data);
      // extMap.ProductCategory = nameRes.data.data || extMap.ProductCategory;
        const readOnlyProps = [
          'productType',
          'MachineModel',
          'Coefficient',
          'Grade',
          'DevelopmentLevel',
          'DevelopmentOrder',
          'PushMode',
          'ProjectDevelopmentOrder',
          'DevelopmentType',
          'ProductSeries',
          'ProjectSection',
          'ProductCategory',
        ];
        formData.value.tyProjectForm.formData.forEach((item) => {
          if (item && extMap.hasOwnProperty(item.prop)) {
            item.value = extMap[item.prop];
            if (readOnlyProps.includes(item.prop)) {
              item.disabled = true;
            }
          }
        });
      }
    }

    const data ={"number":1,"projectName": formData.value.name }
    const res = await request({
      method: 'post',
      url: '/typrjmng/api/v1/project/checkProjectName',
      data: data,
      headers: {
        'Content-Type': 'application/json'
      }
    });

    if (!res.data.data) {
    proxy.$message.error('名称已创建，请重新选择开发令');
    console.log('延迟执行')
    formData.value.projectDevOrder=''
    formData.value.name=''
      const extMap = {
          DevelopmentOrder: '',
          MachineModel:  '',
          productType: '',
          DevelopmentLevel:  '',
          Grade:  '',
          Coefficient:  '',
          PushMode:  '',
          ProjectDevelopmentOrder:  '',
          DevelopmentType:  '',
          ProductCategory:  '',
        };
      formData.value.tyProjectForm.formData.forEach((item) => {
          if (item && extMap.hasOwnProperty(item.prop)) {
            item.value ='';
          
          }
        });

    }else{
          dialogVisible.value = false;
    }
  }

  function handleCancel() {
    dialogVisible.value = false;
  }

  // 清除开发令回显的数据
  function clearDevOrderData() {
    formData.value.name = '';
    formData.value.projectNumber = '';
    formData.value.aircraftModel = '';
    formData.value.devCategory = '';
    formData.value.devLevel = '';
    formData.value.coefficient = '';
    formData.value.boost = '';

    formData.value.owner = [
      {
        name,
        fullname,
        oid,
        otype,
        displayName: `${fullname || ''}${name ? `(${name})` : ''}`
      }
    ];
    // 清除项目经理字段
    formData.value.projectManagerList = [];
    formData.value.remarks = '';
    // 清除状态
    devOrderDetail.value = null;
    isFromDevOrder.value = false;
  }

  function getRowClassName({ row }) {
    return selectedRow.value && selectedRow.value.id === row.id ? 'selected-row' : '';
  }

  function handleKFL(){
    if(formData.value.typeOid){
    searchDevOrder(false, true); // 传递isNewSearch=true，表示执行新搜索
    dialogVisible.value = true;
    }else{
      proxy.$message.warning('请先选择项目类型');
    }
    
}


  return {
    handleKFL,
    devOrderDetail,
    isFromDevOrder,
    formData,
    upload,
    typeOptions,
    planOptions,
    useOptions,
    rules,
    formRef,
    ibaForm,
    tyProjectForm,
    phaseOptions,
    isAddparameter,
    valideIbaForm,
    change,
    changeTemplate,
    dialogVisible,
    tableData,
    total,
    currentPage,
    pageSize,
    selectedRow,
    onSearchProjectDevOrder,
    handleCurrentChange,
    handlePageChange,
    handleConfirm,
    handleCancel,
    searchDevOrderNumber,
    searchDevOrder,
    clearSearch, // 新增
    getRowClassName,
    tableRef,
    clearDevOrderData,
    ProjectTemplateList,
    templateTree,
    templatePopoverVisible,
    treeRef,
    selectedTemplateName,
    toggleDropdown,
    handleClickOutside,
    handleNodeClick
  };
}
